<script setup lang="ts">
import { getCurrentInstance, ref, reactive, watch, onBeforeMount, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  info: '我的云仓',
  // ----
  forAdm: String(proxy.$Phone) === String(logUser.telphone)
})
// ----
const totalCount = ref(0)
// ----
let tag = null
const tags = ref([])
let tagsData = []
let dataFilters = []
const infoSch = ref(null)
const forSearch = ref(proxy.$Store.get('forSearch') || {})
// ----
const forFree = 1
let trueWidth = 0
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const sidebar = ref()
const layer = ref()

/* ---- */
const getSideBar = () => {
  const options = {
    type: 0,
    forall: { show: true, text: '选择行业' },
    itemId: tag || 0,
    list: tags.value,
    callback: (info) => {
      const newItems = []
      if (info) newItems.push(info.value)
      proxy.$Myfun.setSearchRes(proxy, newItems, ['tag'], (result) => { forSearch.value = result })
    }
  }
  proxy.$Myfun.isIndepth(sidebar.value, 'open', options)
}
// ----
const setTagsMenu = () => {
  // --行业分类过滤--
  const tagItems = []
  tagsData.forEach((item, index) => {
    const isHave = dataFilters.some((curItem) => {
      if (String(curItem.tag_id) === String(',' + item.value + ',')) return true
    })
    if (isHave) tagItems.push(item)
  })
  // ----
  tags.value = tagItems
  // --初始化左边菜单--
  if (Number(tags.value.length) > 0) nextTick(() => { getSideBar() })
}
// ----
const getCurrencyInfo = async (callback) => {
  // -- 获取过滤用户信息 && 行业分类 --
  const forFiltData = {
    params: {
      // --是否开通云仓分销--
      'DealerSearch[is_cloud]': 1,
      // --审核通过--
      'DealerSearch[is_stoped]': 1,
      // --完善我的信息--
      'DealerSearch[is_news]': 2,
      // ----
      page: 1,
      PageSize: 1000000000000
    }
  }
  const forTagData = {
    params: {
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('dealer/index', forFiltData),
    proxy.$Axios.get('maincate/index', forTagData)
  ]).then(proxy.$Axios.spread((filtData, tagData) => {
    // --用户信息--
    const filtItems = []
    filtData.items.forEach((item, index) => {
      filtItems.push({
        tag_id: item.maincate_id
      })
    })
    dataFilters = filtItems
    // --行业分类--
    const tagItems = []
    tagData.items.forEach((item, index) => {
      tagItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    tagsData = tagItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  await setTagsMenu()
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 15 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 15,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'dealer/index',
    forData: {
      params: {
        'DealerSearch[name]': infoSch.value,
        'DealerSearch[maincate_id]': tag ? ',' + tag + ',' : undefined,
        // --是否开通云仓分销--
        'DealerSearch[is_cloud]': 1,
        // --审核通过--
        'DealerSearch[is_stoped]': 1,
        // --完善我的信息--
        'DealerSearch[is_news]': 2,
        // ----
        sort: 'SORT_ASC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    totalCount.value = res._meta.totalCount
    // ----
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forName = ''
    proxy.$Myfun.getJsonData(item.ads_content, (resJson) => {
      if (Number(resJson.length) > 0) forName = proxy.$Myfun.setText(resJson[0].name)
    })
    // ----
    let forSign = ''
    let forStyle = { height: `${Math.round(trueWidth / forFree)}px` }
    await proxy.$Myfun.getJsonData(item.avatar, (resJson) => {
      forSign = resJson[0].image
      // ----
      const imgRatio = Number(resJson[0].width / resJson[0].height)
      forStyle = { height: `${Math.round(trueWidth / imgRatio)}px` }
    })
    // ----
    newItems.push({
      id: item.id,
      name: forName,
      image: forSign,
      imgStyle: forStyle
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
  // ----
  getHeadFun(2)
}
// ----
const getHeadFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      proxy.$Myfun.openPage(proxy, 'push', 'ForCloud')
      break
    }
    case 2: {
      const newItems = []
      newItems.push(infoSch.value)
      proxy.$Myfun.setSearchRes(proxy, newItems, ['infoSch'], (result) => { forSearch.value = result })
      break
    }
  }
}
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      proxy.$Myfun.openPage(proxy, 'push', 'CloudHome', { dealer_id: item.id })
      break
    }
  }
}

/* ---- */
watch(() => forSearch.value, (newVal, oldVal) => {
  tag = newVal.tag
  infoSch.value = newVal.infoSch
  // --重新请求数据--
  mescroll.scrollTo(0)
  mescroll.resetUpScroll()
}, { deep: true })

/* ---- */
onBeforeMount(() => {
  tag = forSearch.value.tag
  infoSch.value = forSearch.value.infoSch
})
onMounted(() => {
  getCurrencyInfo(() => {
    setTimeout(() => { if (proxy.$refs.forTrueWidth) trueWidth = proxy.$refs.forTrueWidth.offsetWidth }, 100)
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => {
  if (mescroll) mescroll.destroy()
  proxy.$Store.remove('forSearch')
})
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-flex xw-flex-align">
        <a class="TOP-puretxt TOP-L xw-flex xw-flex-center" @click="getHeadFun(1)" v-if="!user.forAdm">{{user.info}}</a>
        <div class="TOP-sch xw-bg-white xw-radius-3 xw-flex-W1 xw-flex xw-flex-align">
          <em class="far fa-search TOP-L"></em>
          <p class="xw-flex-W1"><input class="schText" type="text" :placeholder="'找入驻商家（' + totalCount + '家）'" v-model.trim="infoSch"/></p>
          <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="infoSch"></em></transition>
          <span class="TOP-btn TOP-R xw-Lfg" @click="getHeadFun(2)">搜索</span>
        </div>
      </div>
    </header>
    <div class="xw-section xw-flex">
      <div class="opp-menu xw-Rfg" v-if="Number(tags.length) > 0"><sidebar-view ref="sidebar"/></div>
      <div class="opp-con xw-bg-white xw-flex-W1">
        <div ref="dataScroll" class="mescroll" @scroll="divScroll">
          <ul class="list-user xw-float" ref="dataList">
            <li class="xw-float-W2" v-for="(item, index) in items"><div class="LUR-con xw-radius-3 xw-act" @click="getAuditFun(1, item)">
              <div class="LUR-img" :style="item.imgStyle"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.image + ')' }"></div></div>
              <div class="LUR-name xw-ellipsis-2">{{item.name}}</div>
            </div></li>
            <div class="list-li xw-float-W2"><div ref="forTrueWidth"></div></div>
          </ul>
        </div>
      </div>
    </div>
    <layer-view ref="layer"/>
  </div>
</template>

<style scoped>
/* ---- */
.opp-con { position: relative; }
.opp-con .mescroll { padding: 0; }

/* ---- */
.list-user { margin: 0 0.5rem; }
.list-user li { padding: 1rem 0 0; }
.LUR-con { margin: 0 0.5rem; background: #f5f5f5; }
.LUR-name { margin: 1rem; height: 4rem; line-height: 2rem; font-size: 1.5rem; }
.list-li div { margin: 0 0.5rem; }
</style>